﻿
_spBodyOnLoadFunctionNames.push('WaitForCalendarToLoad');
var SEPARATOR = "|||";
var MEETINGROOMS = {};
var RESOURCES = {};

var CalendarRoomMapping = {};
GetRoomListBaseOnCalendarID(); // load CalendarRoomMapping for the first time
//console.log(JSON.stringify(CalendarRoomMapping));

function WaitForCalendarToLoad() {
    if (typeof SP.UI.ApplicationPages.CalendarNotify.$4a == 'undefined') {
        // post SP1
        var pwold$4b = SP.UI.ApplicationPages.CalendarNotify.$4b;
        SP.UI.ApplicationPages.CalendarNotify.$4b = function () {
            pwold$4b();
            ColourCalendar();
        }
        SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids = function ($p0) {
            var $v_0 = new Sys.StringBuilder();
            var $v_1 = $p0.length;
            for (var $v_2 = 0; $v_2 < $v_1; $v_2++) {
                this.$7t_2($v_2, $p0[$v_2]);
            }
            for (var $v_3 = 0; $v_3 < $v_1; $v_3++) {
                $v_0.append('<div>');
                this.$I_2.$7o($v_0, $p0[$v_3], $v_3);
                $v_0.append(this.emptY_DIV);
                $v_0.append('</div>');
            }
            this.setInnerHtml($v_0.toString());
            ColourCalendar();
        }
    }
    else {
        // pre SP1
        var pwold$4a = SP.UI.ApplicationPages.CalendarNotify.$4a;
        SP.UI.ApplicationPages.CalendarNotify.$4a = function () {
            pwold$4a();
            ColourCalendar();
        }
        SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids = function ($p0) {
            var $v_0 = new Sys.StringBuilder();
            var $v_1 = $p0.length;
            for (var $v_2 = 0; $v_2 < $v_1; $v_2++) {
                this.$7r_2($v_2, $p0[$v_2]);
            }
            for (var $v_3 = 0; $v_3 < $v_1; $v_3++) {
                $v_0.append('<div>');
                this.$I_2.$7m($v_0, $p0[$v_3], $v_3);
                $v_0.append(this.emptY_DIV);
                $v_0.append('</div>');
            }
            this.setInnerHtml($v_0.toString());
            ColourCalendar();
        }
    }
}

function ColourCalendar() {
    //remove any tooltip that cannot auto-hide when calendar reloaded
    $(".ui-tooltip").remove();


    //highlight today column
    var todayColumnIndex = $(".ms-acal-detail tr.ms-acal-week-top > td:has(.ms-acal-today)").index();
    $(".ms-acal-detail tr > td:nth-child(" + (todayColumnIndex + 1) + ")").addClass("ms-acal-today-custom");


    //Load meeting rooms
    if ($.isEmptyObject(MEETINGROOMS)) {
        GetMeetingRooms();
        //alert("Get meeting rooms success!");
    }

    //Load resources
    if ($.isEmptyObject(RESOURCES)) {
        GetResources();
    }

    //alert($("#v-flat-checkbox-1").prop("checked"));
    $("div.ms-acal-item").each(function () {

        var linkItem = new Url($(this).find("a").attr("href"));
        //alert(calendarUrl.query["ID"]);
        var calendarItemID = linkItem.query["ID"];
        if (calendarItemID.search(".") > -1) {
            calendarItemID = calendarItemID.split(".")[0];
        }
        //alert(calendarItemID);

        //VuCA edited: for improving performance
        var roomID = 0;
        if (CalendarRoomMapping[calendarItemID] != undefined) {
            roomID = CalendarRoomMapping[calendarItemID]; //new one for improving performance
        }
        else {
            //try to reload calendar list to get new items
            CalendarRoomMapping = {}; //reset
            GetRoomListBaseOnCalendarID();

            //check one more time or will use the old one
            if (CalendarRoomMapping[calendarItemID] != undefined) {
                roomID = CalendarRoomMapping[calendarItemID]; //new one for improving performance
            }
//            else { 
//                roomID = GetRoomID(calendarItemID); //old one, slow performance
//            }
        }

        if (MEETINGROOMS[roomID] != undefined)
        {
            var calendarMeetingRoom = MEETINGROOMS[roomID].split("|||");
            var colour = calendarMeetingRoom[0];
            $(this).css('background-color', colour);
            $(this).attr('colour', colour);
            var roomTitle = calendarMeetingRoom[1];
            $(this).attr('meetingroom', roomTitle);
            var divTag = $(this);

            $(".listRooms input").each(function () {

                if (colour == $(this).val()) {
                    if ($(this).prop("checked") == false) {
                        divTag.css("display", "none");
                        return false;
                    }
                }
            });
        }
    });

    /*
    $('a:contains(' + SEPARATOR + ')').each(function () {
        var divParent = $(this).parents('div.ms-acal-item');
        //alert(divParent.text());
        var colourCalendarText = $(this).text();
        var colour = GetCategory(colourCalendarText);
        var actualText = GetActualText(colourCalendarText);
        divParent.css('background-color', colour);
        divParent.attr('colour', SEPARATOR);
        divParent.attr('color', colour);
        divParent.attr('title', actualText);
        $(this).text(actualText);
    });
    */

    /*
    jQuery('a:contains(' + SEPARATOR + ')').each(function (i) {
        $box = jQuery(this).parents('div[title]');
        var colour = GetCategory(this.innerHTML);
        alert(colour);
        $('.listRooms input').each(function () {
            if ($(this).prop('checked')) {
                this.innerHTML = GetActualText(this.innerHTML);
                jQuery($box).attr("title", GetActualText(jQuery($box).attr("title")));
                $box.css('background-color', colour);
            }
            else {
                $box.css('display', 'none');
            }
            //console.log($(this).attr("id") + ": " + $(this).prop('checked') + " --- Value: " + $(this).val());
        });
    });  
    */
}

function GetActualText(originalText) {
    var parts = originalText.split(SEPARATOR);
    return parts[0] + parts[2];
}

function GetCategory(originalText) {
    var parts = originalText.split(SEPARATOR);
    return parts[1];
}

//VuCA added to improve performance
function GetRoomListBaseOnCalendarID() {
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL: $().SPServices.SPGetCurrentSite(),
        listName: $().SPServices.SPListNameFromUrl(),
        CAMLQuery: "<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='ID' /><FieldRef Name='MeetingRoom' /></ViewFields>",
        CAMLQueryOptions: "<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns></QueryOptions>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                CalendarRoomMapping[$(this).attr("ows_ID")] = $(this).attr("ows_MeetingRoom").split(';#')[0];
            });
        }
    });
}

function GetRoomID(calendaID) {
    var roomID = 0;
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL: $().SPServices.SPGetCurrentSite(),
        listName: $().SPServices.SPListNameFromUrl(),
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + calendaID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='MeetingRoom' /><FieldRef Name='ResourceRequest' /></ViewFields>",
        CAMLRowLimit: 1,
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                //alert($(this).attr("ows_MeetingRoom"));
                var meetingRoom = $(this).attr("ows_MeetingRoom");
                roomID = meetingRoom.split(';#')[0];
                //alert($(this).attr("ows_ResourceRequest"));
            });
        }
    });
    return roomID;
}

function GetColorByRoomID(roomID) {
    var color = "#FFFFFF";
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL: $().SPServices.SPGetCurrentSite(),
        listName: "Meeting Rooms",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + roomID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Color' /></ViewFields>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                color = $(this).attr("ows_Color");
            });
        }
    });
    return color;
}

//Get list rooms -> dictionary
function GetMeetingRooms() {
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL: $().SPServices.SPGetCurrentSite(),
        listName: "Meeting Rooms",
        //CAMLQuery: "<Query><Where><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Color' /></ViewFields>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                MEETINGROOMS[$(this).attr("ows_ID")] = $(this).attr("ows_Color") + "|||" + $(this).attr("ows_Title");
                //alert(MEETINGROOMS[(this).attr("ows_ID")]);
            });
        }
    });
}

//Get list resources -> dictionary
function GetResources() {
    $().SPServices({
        operation: "GetListItems",
        async: false,
        webURL: $().SPServices.SPGetCurrentSite(),
        listName: "Resources",
        CAMLQuery: "<Query><Where><And><Eq><FieldRef Name='IsActive' /><Value Type='Boolean'>1</Value></Eq><Eq><FieldRef Name='IsPrivate' /><Value Type='Boolean'>0</Value></Eq></And></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>",
        completefunc: function (xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function () {
                RESOURCES[$(this).attr("ows_ID")] = $(this).attr("ows_Title");
                //alert(RESOURCES[(this).attr("ows_ID")]);
            });
        }
    });
}

//Grant config one day
/*
function GrantOneDay() {
    gantt.config.start_date = new Date(2013, 10, 4, 7, 30); //2013, 10, 4, 7, 30
    gantt.config.end_date = new Date(2013, 10, 4, 19, 30); //2013, 10, 4, 19, 30
    gantt.config.date_grid = "%H:%i";
    gantt.config.scale_unit = "hour"; //"minute";
    gantt.config.time_step = 1;
    gantt.config.duration_unit = 60 * 60 * 1000;
    gantt.config.date_scale = "%H:%i";
    gantt.config.subscales = [
		    { unit: "minute", step: 30, date: "%i" }
	    ];
}
*/
//Grant config one week

//Grant config one month